package com.art.sunflower.util;

import com.art.sunflower.exception.BusyException;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 文件存取工具
 */
public class FileHelper {

    private static final String TREATY = "http";
    private static final Integer PORT = 8075;

    /**
     * 服务器url
     */
    public static String serverURL = TREATY + "://47.104.189.198" + ":" + PORT + File.separator + "static";

    /**
     * 文件url
     */
    public static String fileURL = File.separator + "newsPicture" + File.separator;

    /**
     * 将文件转储到其他路径
     *
     * @param name 文件名
     * @param file 多块文件
     */
    public static void saveTo(String name, MultipartFile file) throws IOException {

        File pathRoot = new File(ResourceUtils.getURL("classpath:").getPath());
        if (!pathRoot.exists()) {
            pathRoot = new File("");
        }

        String saveFile = pathRoot.getAbsolutePath().replace("%20", " ").replace("\\", File.separator) + File.separator + "static" + fileURL;
        System.out.println(saveFile);
        File f = new File(saveFile);
        if (!f.exists()) {
            f.mkdirs();
        }
        FileOutputStream writer = new FileOutputStream(new File(f, name));
        writer.write(file.getBytes());
        writer.flush();
        writer.close();


    }

    //删除文件
    public static void deleteFile(String name) throws IOException {
        File pathRoot = new File(ResourceUtils.getURL("classpath:").getPath());
        if (!pathRoot.exists()) {
            pathRoot = new File("");
        }
        String saveFile = pathRoot.getAbsolutePath().replace("%20", " ").replace("\\", "//") + "//static/" + fileURL + name;
        File f = new File(saveFile);
        boolean res;
        res = f.delete();
        if (!res)
            throw new BusyException();
    }
}
